import Decimal from "decimal.js";

/**
 * 加法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const add = (num1, num2, digit = 9, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) as unknown as string != "0") || (!parseFloat(num2) && parseFloat(num2) as unknown as string != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.plus(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_UP).toString();
};

/**
 * 减法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const subtract = (num1, num2, digit = 9, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) as unknown as string != "0") || (!parseFloat(num2) && parseFloat(num2) as unknown as string != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.minus(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_UP).toString();
};

/**
 * 乘法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const multiply = (num1, num2, digit = 9, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) as unknown as string != "0") || (!parseFloat(num2) && parseFloat(num2) as unknown as string != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.times(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_UP).toString();
};

/**
 * 除法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const divide = (num1, num2, digit = 9, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) as unknown as string != "0") || (!parseFloat(num2) && parseFloat(num2) as unknown as string != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.dividedBy(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_UP).toString();
};
